package com.tingfeng.food.door;

import android.net.Uri;
import android.os.Build;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.RequiresApi;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class CustomWebViewClient extends WebViewClient {

    private static final Map<String, String> MIME_MAP = new HashMap<>();

    static {
        MIME_MAP.put("html", "text/html");
        MIME_MAP.put("htm", "text/html");
        MIME_MAP.put("css", "text/css");
        MIME_MAP.put("js", "application/javascript");
        MIME_MAP.put("json", "application/json");
        MIME_MAP.put("xml", "application/xml");
        MIME_MAP.put("txt", "text/plain");
        MIME_MAP.put("jpg", "image/jpeg");
        MIME_MAP.put("jpeg", "image/jpeg");
        MIME_MAP.put("png", "image/png");
        MIME_MAP.put("gif", "image/gif");
        MIME_MAP.put("svg", "image/svg+xml");
        MIME_MAP.put("woff", "font/woff");
        MIME_MAP.put("woff2", "font/woff2");
        MIME_MAP.put("ttf", "font/ttf");
        MIME_MAP.put("otf", "font/otf");
        MIME_MAP.put("mp4", "video/mp4");
        MIME_MAP.put("webm", "video/webm");
        MIME_MAP.put("ogg", "audio/ogg");
        MIME_MAP.put("mp3", "audio/mpeg");
        MIME_MAP.put("wav", "audio/wav");
        MIME_MAP.put("ico", "image/x-icon");
        MIME_MAP.put("pdf", "application/pdf");
    }

    private String getExtensionFromUrl(String url) {
        try {
            Uri uri = Uri.parse(url);
            String path = uri.getPath();
            if (path != null && path.contains(".")) {
                return path.substring(path.lastIndexOf(".") + 1).toLowerCase();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private String getMimeType(String extension) {
        return MIME_MAP.getOrDefault(extension, "application/octet-stream");
    }
    private ByteArrayOutputStream downloadContent(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(2500);
        connection.setReadTimeout(30000);
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            inputStream = connection.getInputStream();
            byteArrayOutputStream = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len;

            while ((len = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }

            return byteArrayOutputStream;
        } finally {
            if (inputStream != null) inputStream.close();
            if (byteArrayOutputStream != null) byteArrayOutputStream.close();
            connection.disconnect();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        try {
            String url = request.getUrl().toString();
            ByteArrayOutputStream byteArrayOutputStream = downloadContent(url);

            if (byteArrayOutputStream == null) return null;

            String extension = getExtensionFromUrl(url);
            String mimeType = getMimeType(extension);

            InputStream stream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            return new WebResourceResponse(mimeType, "UTF-8", stream);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}